package cn.mumzone.pos.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.ReserveOrderEntity;
import cn.mumzone.pos.model.ServiceEntity;
import cn.mumzone.pos.presenter.AddServePresenter;
import cn.mumzone.pos.presenter.contract.AddServeContract;
import cn.mumzone.pos.ui.adapter.ADA_AddServiceList;
import cn.mumzone.pos.ui.adapter.ADA_CartServicesSimple;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;
import cn.mumzone.pos.util.PopupUtil;
import retrofit2.http.POST;

/**
 * Created By Dlx
 * on 2019/7/8
 */
public class ACT_AddServe extends BaseActivity<AddServePresenter> implements AddServeContract.View, ADA_AddServiceList.AddServeListener, ADA_CartServicesSimple.OnItemDeleteListener {
    @BindView(R.id.rv_service_list)
    LRecyclerView rvServiceList;
    @BindView(R.id.ll_empty_service)
    LinearLayout llEmptyService;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_grade)
    TextView etGrade;
    @BindView(R.id.rv_cart_services)
    LRecyclerView rvCartServices;
    @BindView(R.id.ll_cart_services)
    LinearLayout llCartServices;
    @BindView(R.id.ll_empty_cart)
    LinearLayout llEmptyCart;
    @BindView(R.id.tv_select_count_title)
    TextView tvSelectCountTitle;
    @BindView(R.id.btn_settle)
    LoadingButton btnSettle;
    @BindView(R.id.et_server_name)
    TextView etServerName;

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    private LRecyclerViewAdapter lRecyclerViewAdapter, rRecyclerViewDecorationAdapter;
    private ADA_AddServiceList adapter;
    private ADA_CartServicesSimple cardAdapter;

    private String appointmentTime;
    private String technicianId;
    private String technicianName;
    private String techniacianLabel;
    private String appointmentMaxEndTime;

    private String memberPhone;
    private String memberId = "";
    private String memberName = "";
    private boolean isMember = false;
    private int currentDays = 0;

    private long currentTime;
    private long maxTime;
    private long startTime;

    public static final String CURRENT_DAYS = "current_days";
    public static final String TECHNICIAN_LABEL = "technician_label";
    public static final String NEXT_SERVICE_START_TIME = "next_service_start_time";

    private PopupWindow mPopup;

    private List<ServiceEntity> cartList = new ArrayList<>();


    public static void startAc(Context context, String time, String nextServiceTime, String technicianLabel, String technicianName, String serveId, int currentDays) {

        Intent intent = new Intent(context, ACT_AddServe.class);
        Bundle bundle = new Bundle();

        bundle.putSerializable(AppConstants.APPOINTMENT_TIME, time);
        bundle.putSerializable(AppConstants.TECHNICIAN_ID, serveId);
        bundle.putSerializable(AppConstants.TECHNICIAN_NAME, technicianName);
        bundle.putSerializable(CURRENT_DAYS, currentDays);
        bundle.putSerializable(TECHNICIAN_LABEL, technicianLabel);
        bundle.putSerializable(NEXT_SERVICE_START_TIME, nextServiceTime);

        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);

        appointmentTime = extras.getString(AppConstants.APPOINTMENT_TIME);
        technicianId = extras.getString(AppConstants.TECHNICIAN_ID);
        technicianName = extras.getString(AppConstants.TECHNICIAN_NAME);
        currentDays = extras.getInt(CURRENT_DAYS, 0);
        techniacianLabel = extras.getString(TECHNICIAN_LABEL);
        appointmentMaxEndTime = extras.getString(NEXT_SERVICE_START_TIME);

        currentTime = AppDateUtil.getStringToDate(appointmentTime, AppDateUtil.YYYY_MM_DD_HH_MM);
        startTime = currentTime;
        maxTime = AppDateUtil.getStringToDate(appointmentMaxEndTime, AppDateUtil.YYYY_MM_DD_HH_MM);
    }

    @Override
    protected void initEventAndData() {
        mPresenter.initEvent();

        etServerName.setText(technicianName + "(" + techniacianLabel + ")");
        etGrade.setText(appointmentTime);

        GridLayoutManager serviceManager = new GridLayoutManager(mContext, 3);
        rvServiceList.setLayoutManager(serviceManager);
        adapter = new ADA_AddServiceList(this);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        rvServiceList.setAdapter(lRecyclerViewAdapter);
        adapter.setAddServeListener(this);

        cardAdapter = new ADA_CartServicesSimple(this);
        rvCartServices.setLayoutManager(new LinearLayoutManager(mContext));
        rRecyclerViewDecorationAdapter = new LRecyclerViewAdapter(cardAdapter);
        rvCartServices.setAdapter(rRecyclerViewDecorationAdapter);
        cardAdapter.setOnItemDeleteListener(this);
        rvCartServices.setPullRefreshEnabled(false);
        GridItemDecoration cartServiceDivider = new GridItemDecoration.Builder(mContext)
                .setVertical(R.dimen.dp_12)
                .setColorResource(android.R.color.transparent)
                .build();
        rvCartServices.addItemDecoration(cartServiceDivider);

        mPresenter.getServeList(memberId);

        initEtphone();
        onCartChange();

        showPopupHint();
    }

    private void onCartChange() {
        double amount = 0.00d;
        if (cartList.size() == 0) {
            btnSettle.setEnabled(false);
        } else {
            btnSettle.setEnabled(true);
        }
        for (ServiceEntity entity : cartList) {
            if (isMember) {
                amount = BigDecimalUtil.add(amount, entity.getMemberPrice());

            } else {
                amount = BigDecimalUtil.add(amount, entity.getPrice());
            }
        }
        tvSelectCountTitle.setText(StringSpanUtils.init().addForegroundColorHighLight(getResources().getColor(R.color.order_status_close), "总共选择 ")
                .addRelativeScale(1.3f, cartList.size() + "")
                .setForeColorWithKeyAndPosition(cartList.size() + "", 1, getResources().getColor(R.color.title_text_color))
                .addForegroundColorHighLight(getResources().getColor(R.color.order_status_close), " 项     共计")
                .addForegroundColorHighLight(getResources().getColor(R.color.settle_red), "  ￥" + amount)
                .setScaleWithKeyAndPosition("  ￥" + amount, 3, 1.3f).build());
    }

    @Override
    protected int getLayout() {
        return R.layout.act_serve;
    }


    @OnClick({R.id.btn_settle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_settle:
                PopupUtil.dismissPopup(PopupUtil.RESERVE_MAKE_ORDER, mPopup);
                if (checkEmpty()) {
                    mPresenter.doAddReserve(memberId, memberName, memberPhone, appointmentTime, cartList);
                    btnSettle.startLoading("正在预约");
                }
                break;
        }
    }

    private boolean checkEmpty() {

        memberPhone = etPhone.getText().toString().trim();
        memberName = etName.getText().toString().trim();
        if (StringUtils.isEmpty(memberPhone)) {
            PosToast.INSTANCE.makeShortToast(mContext, "手机号不能为空");
            return false;
        }
        if (!StringUtils.isPhone(memberPhone)) {
            PosToast.INSTANCE.makeShortToast(mContext, "请输入正确的手机号");
            return false;
        }
        if (StringUtils.isEmpty(memberName)) {
            PosToast.INSTANCE.makeShortToast(mContext, "姓名不能为空");
            return false;
        }
        return true;
    }

    private void initEtphone() {
        tvName.setText(StringSpanUtils.init().
                addForegroundColorHighLight(getResources().getColor(R.color.highlight_text_color), "*")
                .addForegroundColorHighLight(getResources().getColor(R.color.title_text_color), "姓名").build());

        tvPhone.setText(StringSpanUtils.init().
                addForegroundColorHighLight(getResources().getColor(R.color.highlight_text_color), "*")
                .addForegroundColorHighLight(getResources().getColor(R.color.title_text_color), "电话").build());


        etPhone.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 11) {
                    mPresenter.searchMember(editable.toString().trim());
                } else {
                    if (!TextUtils.isEmpty(etName.getText().toString()) || isMember) {
                        etName.setText("");
                        isMember = false;
                        mPresenter.getServeList("");
                    }
                }
            }
        });
    }

    @Override
    public void showServeList(List<ServiceEntity> entity) {
        adapter.setIsMember(isMember);
        adapter.setData(entity);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showServeWithCardList(List<ServiceEntity> entity) {
        List<ServiceEntity> datas = adapter.getData();
        if (datas != null && entity.size() == datas.size()) {
            for (int i = 0; i < entity.size(); i++) {
                entity.get(i).setSelectCount(datas.get(i).getSelectCount());
            }
            adapter.setIsMember(isMember);
            adapter.setData(entity);
            adapter.notifyDataSetChanged();
        } else {
            PosToast.INSTANCE.makeShortToast(mContext, "两次数组不匹配");
        }
        onCartChange();
    }

    @Override
    public void showSettleSuccess() {
        finish();
    }

    @Override
    public void showAddReserveSuccess(ReserveOrderEntity reserveOrderEntity) {
        PosToast.INSTANCE.makeSuccessToast(mContext, "预约成功");
        btnSettle.stopLoading("预约成功");
        finish();
    }

    @Override
    public void onSearchMemberSuccess(MemberEntity memberEntity) {
        memberId = memberEntity.getMemberId();
        etName.setText(memberEntity.getName());
        mPresenter.getServeListWithMemberId(memberEntity.getMemberId());
        isMember = true;
    }

    @Override
    public void onNoMemberFound() {
        memberId = "";
        isMember = false;
    }

    @Override
    public void addServeFailed() {
//        PosToast.INSTANCE.makeShortToast(mContext,"预约失败");
        btnSettle.stopLoading("预约");
    }

    /**
     * 当服务列表子条目被点击，回调此函数用以处理数据，同步到已选择列表
     *
     * @param position 被点击的条目位置
     * @param entity   被点击的条目实体
     */
    @Override
    public void onServeCardClick(int position, ServiceEntity entity) {

        Log.e("onServeCardClick: ", "serviceTime:" + entity.getServiceTime() + "  currentTime:" + currentTime + "  maxTime:" + maxTime);
//        if ((currentTime + (Long.parseLong(entity.getServiceTime()) * 60 * 1000)) > maxTime && !StringUtils.isTrue(entity.getUseTime())) {
        if ((currentTime + (Long.parseLong(entity.getServiceTime()) * 60 * 1000)) > maxTime) {
            PosToast.INSTANCE.makeShortToast(mContext, "当前时间,该技师只有" + ((maxTime - startTime) / 60000) + "分钟空闲~");
            return;
        }
//        if (!StringUtils.isTrue(entity.getUseTime()))// 0 占用 1不占用 不占用才计算时长
//        {
        currentTime = currentTime + (Long.parseLong(entity.getServiceTime()) * 60 * 1000);
//        }
        adapter.getData().get(position).setSelectCount(entity.getSelectCount() + 1);
        adapter.notifyItemChanged(position);

        entity.setPositionInServeList(position);
        entity.setTechnicianId(technicianId);
        entity.setTechnicianName(technicianName);
        cartList.add(entity);
        cardAdapter.setDatas(cartList);
        onCartChange();
    }

    /**
     * 当已选择列表 条目被删除时回调此函数，用以同步通知服务列表刷新选中数量
     *
     * @param position_in_service_list 被删除条目位于服务列表的位置
     */
    @Override
    public void onServiceDelete(int position_in_service_list) {
//        if (!StringUtils.isTrue(adapter.getData().get(position_in_service_list).getUseTime())) {
        currentTime = currentTime - (Long.parseLong(adapter.getData().get(position_in_service_list).getServiceTime()) * 60 * 1000);
//        }
        adapter.getData().get(position_in_service_list).setSelectCount(adapter.getData().get(position_in_service_list).getSelectCount() - 1);
        adapter.notifyItemChanged(position_in_service_list);
        onCartChange();
    }

    public void showPopupHint() {
        btnSettle.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPopup = PopupUtil.showBlackBgPopup(btnSettle, PopupUtil.RESERVE_MAKE_ORDER, "点击创建预约单", PopupUtil.LEFT_TOP);
            }
        }, 800);
    }

}
